import datetime


class User:
    user = {"admin": {"passwd": "admin", "money": 0, 'history': []}}

    def __init__(self, name, passwd):
        self.name = name
        self.passwd = passwd

    def chongzhi(self):
        chong = int(input("请输入你想充值的金额"))
        self.user[self.name]['money'] = self.user[self.name]['money'] + chong
        self.user[self.name]['history'].append(f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} 充值{chong} 剩余余额{self.user[self.name]["money"]}')

    def chaxun(self):
        chaxun = input("输入0查询上一次购买记录，输入1查询历史购买记录(只显示近50次购买记录)")
        if chaxun == '0':
            if len(self.user[self.name]['history']) >= 1:
                print(self.user[self.name]['history'][-1])
            else:
                print('无购买记录！')
        if chaxun == '1':
            if len(self.user[self.name]['history']) >= 50:
                print(self.user[self.name]['history'][-51:])
            else:
                end = len(self.user[self.name]['history']) + 1
                print(self.user[self.name]['history'][-end:])

    def login(self):
        if self.name in self.user.keys():
            if self.passwd == self.user[self.name]["passwd"]:
                print(f"登陆成功！当前用户余额{self.user[self.name]['money']}")
                return True
            else:
                print("密码错误！")
                return False
        else:
            print("账号不存在！")
            return False

    def CreateUser(self):
        while True:
            cname = input("请输入用户名")
            cpasswd = input("请输入密码")
            if not cname in self.user.keys():
                self.user[cname] = {"passwd": cpasswd, "money": 0, 'history': []}
                print('创建用户成功，请重新登录！')
                break
            else:
                print("用户名已存在")

    def buy_goods(self, good, weight):
        weight = int(weight)
        if good in Goods.goods.keys():
            if weight > Goods.goods[good]['store']:
                print("库存不足！")
            else:
                pay = weight * Goods.goods[good]['price']
                if self.user[self.name]['money'] >= pay:
                    self.user[self.name]['money'] -= pay
                    Goods.goods[good]['store'] -= weight
                    print(f"购买成功，{self.name}剩余{self.user[self.name]['money']}元， "
                          f"{good}剩余库存{Goods.goods[good]['store']}")
                    self.user[self.name]['history'].append(f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} 购买商品{good} 数量{weight} 单价{Goods.goods[good]["price"]} 总计{pay} 剩余余额{self.user[self.name]["money"]}')
                else:
                    print("余额不足")
        else:
            print('商品不存在！')


class Goods:
    goods = {'apple': {"classify": "fruits", 'price': 8, 'store': 30},
             'orange': {"classify": "fruits", 'price': 4, 'store': 100}}

    # def admin


print('{0:^50}'.format('三乐购物系统'))
while True:
    ui1 = input(f'输入1用户登录\n输入2创建用户\n输入3查看商品\n输入4退出程序\n')
    if ui1 == '1':
        name = input('请输入用户名')
        passwd = input('请输入密码')
        if User(name, passwd).login():
            while True:
                ui2 = input(f'输入1开始购物\n输入2查询流水\n输入3查看商品\n输入4尼冲Q币🐎？\n输入5退出登录\n')
                if ui2 == '1':
                    good = input('请输入你想购买的物品')
                    weight = input('请输入你想购买的数量')
                    User(name, passwd).buy_goods(good, weight)
                elif ui2 == '2':
                    User(name, passwd).chaxun()
                elif ui2 == '3':
                    print(Goods.goods)
                elif ui2 == '4':
                    User(name, passwd).chongzhi()
                elif ui2 == '5':
                    break
    elif ui1 == '2':
        User('admin', 'admin').CreateUser()
    elif ui1 == '3':
        print(Goods.goods)
    elif ui1 == '4':
        print('欢迎下次光临！')
        break
